package com.ybg.share.core.shareapi;

import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvRow;
import cn.hutool.core.text.csv.CsvUtil;
import com.ybg.framework.dto.AbstractJob;
import com.ybg.framework.enums.SyncPolicyEnum;
import com.ybg.share.core.dbapi.entity.ShareStock;
import com.ybg.share.core.dbapi.entity.ShareStockDayK;
import com.ybg.share.core.dbapi.service.ShareStockDayKService;
import com.ybg.share.utils.ThreadUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

public abstract class AbstractStockDayKApi {
    @Autowired
    ShareStockDayKService shareStockDayKService;

    /**
     * 执行
     *
     * @return 是否执行
     */
    public Boolean execute(ShareStock stock, SyncPolicyEnum policy) {
        saveToDB(stock, policy);
        return Boolean.TRUE;
    }

    public abstract String getUrl(ShareStock stock, SyncPolicyEnum policy);

    public abstract String getMarket();

    public abstract String getStartTime(ShareStock stock, SyncPolicyEnum policy);

    private void saveToDB(ShareStock stock, SyncPolicyEnum policy) {

        //   List<ShareStockDayK> shareStockDayKList = new ArrayList<>();
        CloseableHttpClient client;
        CloseableHttpResponse response;
        try {
            HttpGet httpGet = new HttpGet(getUrl(stock, policy));
            client = HttpClients.createDefault();
            response = client.execute(httpGet);
            HttpEntity entity = response.getEntity();
            BufferedReader in = new BufferedReader(new InputStreamReader(entity.getContent(), "GBK"));
            CsvData csvData = CsvUtil.getReader().read(in);
            List<CsvRow> rows = csvData.getRows();
            if (rows.size() == 1) {
                return;
            }
            rows = rows.stream().filter(x -> !x.get(0).equals("日期")).collect(Collectors.toList());
            for (CsvRow row : rows) {

                ShareStockDayK shareStockDayK = new ShareStockDayK();

                int count = 0;
                shareStockDayK.setRefDate(row.get(count++));
                shareStockDayK.setCode(row.get(count++).substring(1));
                shareStockDayK.setName(row.get(count++));
                shareStockDayK.setClosePrice(toNum(row.get(count++)));
                shareStockDayK.setMaxPrice(toNum(row.get(count++)));
                shareStockDayK.setMinPrice(toNum(row.get(count++)));
                shareStockDayK.setOpenPrice(toNum(row.get(count++)));
                shareStockDayK.setBeforeClose(toNum(row.get(count++)));
                shareStockDayK.setChangeAmount(toNum(row.get(count++)));
                shareStockDayK.setChangeRange(toNum(row.get(count++)));
                shareStockDayK.setTurnoverRate(toNum(row.get(count++)));
                shareStockDayK.setTradeNum(toNum(row.get(count++)).longValue());
                shareStockDayK.setTradeMoney(toNum(row.get(count++)));
                shareStockDayK.setTotalValue(toNum(row.get(count++)).longValue());
                shareStockDayK.setCirculationValue(toNum(row.get(count++)).longValue());
                shareStockDayK.setTurnoverNum(0L);//倒出来的数据为None
                shareStockDayK.setMarket(getMarket());
                shareStockDayK.setStockId(stock.getId());
                // shareStockDayKList.add(shareStockDayK);
                if (shareStockDayK.getOpenPrice().compareTo(BigDecimal.ZERO) < 1) {
                    continue;
                }
//                ThreadUtil.execute(() -> {
//                    //因为数据不会变，所以只需要忽略
//                    shareStockDayKService.saveIgnore(shareStockDayK);
//                });
                ThreadUtil.execute(new AbstractJob(shareStockDayK) {
                    @Override
                    public void execute() {
                        ShareStockDayK shareStockDayK = (ShareStockDayK) getParams();
                        shareStockDayKService.saveIgnore(shareStockDayK);
                    }
                });

            }
            String result;
            int index = 0;

            while ((result = in.readLine()) != null) {
                if (index != 0) {

                }
                index++;
            }
            if (response != null) {
                response.close();
            }
            if (client != null) {
                client.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private BigDecimal toNum(String value) {
        try {
            return new BigDecimal(value);
        } catch (Exception e) {

        }
        return BigDecimal.ZERO;

    }
}
